import unittest
import tempfile
import os
from L2 import find_max_circular_subarray_sum, read_array_from_file  # 源代码在L2.py中

class TestCircularSubarray(unittest.TestCase):
    def test_normal_subarray(self):
        arr = [1, -2, 3, 4, -5]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, 7)
        self.assertEqual(start, 2)
        self.assertEqual(end, 3)

    def test_circular_subarray(self):
        arr = [5, -3, 5]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, 10)
        self.assertEqual(start, 2)
        self.assertEqual(end, 0)

    def test_all_positive(self):
        arr = [1, 2, 3, 4]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, 10)
        self.assertEqual(start, 0)
        self.assertEqual(end, 3)

    def test_all_negative(self):
        arr = [-1, -2, -3, -4]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, -1)
        self.assertEqual(start, 0)
        self.assertEqual(end, 0)

    def test_with_zero(self):
        arr = [0, -1, 2, -3, 0]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, 2)
        self.assertEqual(start, 2)
        self.assertEqual(end, 2)

    def test_single_element(self):
        arr = [5]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, 5)
        self.assertEqual(start, 0)
        self.assertEqual(end, 0)

    def test_two_elements(self):
        arr = [3, -1]
        max_sum, start, end = find_max_circular_subarray_sum(arr)
        self.assertEqual(max_sum, 3)
        self.assertEqual(start, 0)
        self.assertEqual(end, 0)

    def test_read_array_from_file(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
            f.write("1 2 3 4 5")
            temp_file_name = f.name
        try:
            arr = read_array_from_file(temp_file_name)
            self.assertEqual(arr, [1, 2, 3, 4, 5])
        finally:
            os.unlink(temp_file_name)

    def test_read_empty_file(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
            temp_file_name = f.name
        try:
            arr = read_array_from_file(temp_file_name)
            self.assertEqual(arr, [])
        finally:
            os.unlink(temp_file_name)

    def test_read_large_array(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
            # 生成105个元素
            f.write(" ".join([str(i) for i in range(105)]))
            temp_file_name = f.name
        try:
            arr = read_array_from_file(temp_file_name)
            self.assertEqual(len(arr), 100)
            self.assertEqual(arr, list(range(100)))
        finally:
            os.unlink(temp_file_name)

if __name__ == '__main__':
    unittest.main()